home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 1.toast / Sample Code / Networking / OTSimpleServerHTTP / OTSimpleServerHTTP.c < prev    next >
Encoding:
Text File  |  2000-09-28  |  22.2 KB  |  731 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        OTSimpleServerHTTP.c
  3.  
  4.     Contains:    Implementation of the simple HTTP server sample.
  5.  
  6.     Written by: Quinn "The Eskimo!"
  7.  
  8.     Copyright:    Copyright © 1997-1999 by Apple Computer, Inc., All Rights Reserved.
  9.  
  10.                 You may incorporate this Apple sample source code into your program(s) without
  11.                 restriction. This Apple sample source code has been provided "AS IS" and the
  12.                 responsibility for its operation is yours. You are not permitted to redistribute
  13.                 this Apple sample source code as "Apple sample source code" after having made
  14.                 changes. If you're going to re-distribute the source, we require that you make
  15.                 it clear in the source that the code was descended from Apple sample source
  16.                 code, but that you've made changes.
  17.  
  18.     Change History (most recent first):
  19.                 7/23/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  20.                 
  21.  
  22. */
  23.  
  24. /////////////////////////////////////////////////////////////////////
  25. // The OT debugging macros in <OTDebug.h> require this variable to
  26. // be set.
  27. #include <Files.h>
  28. #include <Memory.h>
  29. #include <TextUtils.h>
  30. #ifndef qDebug
  31. #define qDebug    1
  32. #endif
  33.  
  34. /////////////////////////////////////////////////////////////////////
  35. // Pick up all the standard OT stuff.
  36.  
  37. #include <OpenTransport.h>
  38.  
  39. /////////////////////////////////////////////////////////////////////
  40. // Pick up all the OT TCP/IP stuff.
  41.  
  42. #include <OpenTptInternet.h>
  43.  
  44. /////////////////////////////////////////////////////////////////////
  45. // Pick up the OTDebugBreak and OTAssert macros.
  46.  
  47. #include <OTDebug.h>
  48.  
  49. /////////////////////////////////////////////////////////////////////
  50. // Pick up the various Thread Manager APIs.
  51.  
  52. #include <Threads.h>
  53.  
  54. /////////////////////////////////////////////////////////////////////
  55.  
  56. #include <stdio.h>
  57.  
  58. /////////////////////////////////////////////////////////////////////
  59. // Pick up our own prototype.
  60.  
  61. #include "OTSimpleServerHTTP.h"
  62.  
  63. /////////////////////////////////////////////////////////////////////
  64. // OTDebugStr is not defined in any OT header files, but it is
  65. // exported by the libraries, so we define the prototype here.
  66.  
  67. extern pascal void OTDebugStr(const char* str);
  68.  
  69. /////////////////////////////////////////////////////////////////////
  70. // When this boolean is to set true, this module assumes that the
  71. // host application is trying to quit and all the threads created by
  72. // this module start dying.  See the associated comment in the
  73. // YieldingNotifier routine.
  74.  
  75. extern Boolean gQuitNow = false;
  76.  
  77. // RRK Comments added 8/27/97
  78. // DoNegotiateIPReuseAddrOption is defined in the file
  79. // EnableIPReuseAddrSample.c.  This call uses the OTOptionManagement function
  80. // to set the IP level ResuseAddr option so that an IP address can be
  81. // reused on immediate relaunch of the application.
  82. extern OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode);
  83.  
  84. /////////////////////////////////////////////////////////////////////
  85.  
  86. static pascal void YieldingNotifier(EndpointRef ep, OTEventCode code, 
  87.                                        OTResult result, void* cookie)
  88.     // This simple notifier checks for kOTSyncIdleEvent and
  89.     // when it gets one calls the Thread Manager routine
  90.     // YieldToAnyThread.  Open Transport sends kOTSyncIdleEvent
  91.     // whenever it's waiting for something, eg data to arrive
  92.     // inside a sync/blocking OTRcv call.  In such cases, we
  93.     // yield the processor to some other thread that might
  94.     // be doing useful work.
  95.     //
  96.     // The routine also checks the gQuitNow boolean to see if the
  97.     // the host application wants us to quit.  This roundabout technique
  98.     // avoids a number of problems including:
  99.     //
  100.     // 1. Threads stuck inside OT synchronous calls -- You can't just
  101.     //    call DisposeThread on a thread that's waiting for an OT
  102.     //    synchronous call to complete.  Trust me, it would be bad!
  103.     //    Instead, this routine calls OTCancelSynchronousCalls to get
  104.     //    out of the call.  The given error code (userCanceledErr) 
  105.     //    propagates out to the caller, which causes the calling
  106.     //    thread to eventually terminate.
  107.     // 2. Threads holding resources -- You can't just DisposeThread
  108.     //    a networking thread because it might be holding resouces,
  109.     //    like memory or endpoints, that need to be cleaned up properly.
  110.     //    Cancelling the thread in this way causes the thread's own
  111.     //    code to clean up those resources just like it would for any
  112.     //    any other error.
  113.     //
  114.     // I could have used a more sophisticated mechanism to support
  115.     // quitting (such as a boolean per thread, or returning some
  116.     // "thread object" to which the application can send a "cancel"
  117.     // message, but this way is easy and works just fine for this
  118.     // simple sample
  119. {
  120.     #pragma unused(result)
  121.     #pragma unused(cookie)
  122.     OSStatus junk;
  123.     
  124.     switch (code) {
  125.         case kOTSyncIdleEvent:
  126.             junk = YieldToAnyThread();
  127.             OTAssert("YieldingNotifier: YieldToAnyThread failed", junk == noErr);
  128.             
  129.             if (gQuitNow) {
  130.                 junk = OTCancelSynchronousCalls(ep, userCanceledErr);
  131.                 OTAssert("YieldingNotifier: Failed to cancel", junk == noErr);
  132.             }
  133.             break;
  134.         default:
  135.             // do nothing
  136.             break;
  137.     }
  138. }
  139.  
  140. /////////////////////////////////////////////////////////////////////
  141.  
  142. static void SetDefaultEndpointModes(EndpointRef ep)
  143.     // This routine sets the supplied endpoint into the default
  144.     // mode used in this application.  The specifics are:
  145.     // blocking, synchronous, and using synch idle events with
  146.     // the standard YieldingNotifier.
  147. {
  148.     OSStatus junk;
  149.     
  150.     junk = OTSetBlocking(ep);
  151.     OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
  152.     junk = OTSetSynchronous(ep);
  153.     OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
  154.     junk = OTInstallNotifier(ep, &YieldingNotifier, ep);
  155.     OTAssert("SetDefaultEndpointModes: Could not install notifier", junk == noErr);
  156.     junk = OTUseSyncIdleEvents(ep, true);
  157.     OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
  158. }
  159.  
  160. /////////////////////////////////////////////////////////////////////
  161.  
  162. static OSStatus OTSndQ(EndpointRef ep, void *buf, size_t nbytes)
  163.     // My own personal wrapper around the OTSnd routine that cleans
  164.     // up the error result.
  165. {
  166.     OTResult bytesSent;
  167.     
  168.     bytesSent = OTSnd(ep, buf, nbytes, 0);
  169.     if (bytesSent >= 0) {
  170.     
  171.         // Because we're running in synchronous blocking mode, OTSnd
  172.         // should not return until it has sent all the bytes unless it
  173.         // gets an error.  If it does, we want to hear about it.
  174.         OTAssert("OTSndQ: Not enough bytes sent", bytesSent == nbytes);
  175.     
  176.         return (noErr);
  177.     } else {
  178.         return (bytesSent);
  179.     }
  180. }
  181.  
  182. /////////////////////////////////////////////////////////////////////
  183.  
  184. static OSErr FSReadQ(short refNum, long count, void *buffPtr)
  185.     // My own wrapper for FSRead.  Whose bright idea was it for
  186.     // it to return the count anyway!
  187. {
  188.     OSStatus err;
  189.     long tmpCount;
  190.     
  191.     tmpCount = count;
  192.     err = FSRead(refNum, &count, buffPtr);
  193.     
  194.     OTAssert("FSReadQ: Did not read enough bytes", (err != noErr) || (count == tmpCount));
  195.     
  196.     return (err);
  197. }
  198.  
  199. /////////////////////////////////////////////////////////////////////
  200.  
  201. static Boolean StringHasSuffix(const char *str, const char *suffix)
  202.     // Returns true if the end of str is suffix.
  203. {
  204.     Boolean result;
  205.     
  206.     result = false;
  207.     if ( OTStrLength(str) >= OTStrLength(suffix) ) {
  208.         if ( OTStrEqual(str + OTStrLength(str) - OTStrLength(suffix) , suffix) ) {
  209.             result = true;
  210.         }
  211.     }
  212.     
  213.     return (result);
  214. }
  215.  
  216. static OSStatus ExtractRequestedFileName(const char *buffer,
  217.                                             char *fileName, char *mimeType)
  218.     // Assuming that buffer is a C string contain an HTTP request,
  219.     // extract the name of the file that's being requested.
  220.     // Also check to see if the file has one of the common suffixes,
  221.     // and set mimeType appropriately.
  222.     //
  223.     // Obviously this routine should use Internet Config to
  224.     // map the file type/creator/extension to a MIME type,
  225.     // but I don't want to complicate the sample with that code.
  226. {
  227.     OSStatus err;
  228.     
  229.     // Default the result to empty.
  230.     fileName[0] = 0;
  231.     
  232.     // Scan the request looking for the fileName.  Obviously this is not
  233.     // a very good validation of the request, but this is an OT sample,
  234.     // not an HTTP one.  Also note that we require HTTP/1.0, but some
  235.     // ancient clients might just generate "GET %s<cr><lf>"
  236.     
  237.     (void) sscanf(buffer, "GET %s HTTP/1.0", fileName);
  238.     
  239.     // If the file name is still blank, scanf must have failed.
  240.     // Note that I don't rely on the result from scanf because in a
  241.     // previous life I learnt to mistrust it.
  242.     
  243.     if (fileName[0] == 0) {
  244.         err = -1;
  245.     } else {
  246.     
  247.         // So the request is cool.  Normalise the file name.
  248.         // Requests for the root return "index.html".
  249.         
  250.         if ( OTStrEqual(fileName, "/") ) {
  251.             OTStrCopy(fileName, "index.html");
  252.         }
  253.         
  254.         // Remove the prefix slash.  Note that we don't deal with
  255.         // "slashes" embedded in the fileName, so we don't handle
  256.         // any directories other than the root.  This would be
  257.         // easy to do, but again this is not an HTTP sample.
  258.         
  259.         if ( fileName[0] == '/' ) {
  260.             BlockMoveData(&fileName[1], &fileName[0], OTStrLength(fileName));
  261.         }
  262.     
  263.         // Set mimeType based on the file's suffix.
  264.         
  265.         if ( StringHasSuffix(fileName, ".html") ) {
  266.             OTStrCopy(mimeType, "text/html");
  267.         } else if ( StringHasSuffix(fileName, ".gif") ) {
  268.             OTStrCopy(mimeType, "image/gif");
  269.         } else if ( StringHasSuffix(fileName, ".jpg") ) {
  270.             OTStrCopy(mimeType, "image/jpeg");
  271.         } else {
  272.             OTStrCopy(mimeType, "text/plain");
  273.         }
  274.         err = noErr;
  275.     }
  276.     
  277.     #if qDebug
  278.         printf("ExtractRequestedFileName: Returning %d, “%s”, “%s”\n", err, fileName, mimeType);
  279.     #endif
  280.     
  281.     return (err);
  282. }
  283.  
  284. /////////////////////////////////////////////////////////////////////
  285.  
  286. // The worker thread reads characters one at a time from the endpoint
  287. // and uses the following state machine to determine when the request is
  288. // finished.  For HTTP/1.0 requests, the request is terminated by
  289. // two consecutive CR LF pairs.  Each time we read one of the appropriate
  290. // characters we increment the state until we get to kDone, at which
  291. // point we go off to process the request.
  292.  
  293. enum {
  294.     kWorkerWaitingForCR1,
  295.     kWorkerWaitingForLF1,
  296.     kWorkerWaitingForCR2,
  297.     kWorkerWaitingForLF2,
  298.     kWorkerDone
  299. };
  300.  
  301. // This is the size of the transfer buffer that each worker thread
  302. // allocates to read file system data and write network data.
  303.  
  304. enum {
  305.     kTransferBufferSize = 4096
  306. };
  307.  
  308. // WorkerContext holds the information needed by a worker endpoint to
  309. // operate.  A WorkerContext is created by the listener endpoint
  310. // and passed as the thread parameter to the worker thread.  If the
  311. // listener successfully does this, it's assumed that the worker
  312. // thread has taken responsibility for freeing the context.
  313.  
  314. struct WorkerContext {
  315.     EndpointRef worker;
  316.     short vRefNum;
  317.     long dirID;
  318. };
  319. typedef struct WorkerContext WorkerContext, *WorkerContextPtr;
  320.  
  321. // The two buffers hold standard HTTP responses.  The first is the 
  322. // default text we spit out when we get an error.  The second is
  323. // the header that we use when we successfully field a request.
  324. // Again note that this sample is not about HTTP, so these responses
  325. // are probably not particularly compliant to the HTTP protocol.
  326.  
  327. char gDefaultOutputText[] = "HTTP/1.0 200 OK\15\12Content-Type: text/html\15\12\15\12<H1>Say what!</H1><P>\15\12Error Number (%d), Error Text (%s)";
  328. char gHTTPHeader[] = "HTTP/1.0 200 OK\15\12Content-Type: %s\15\12\15\12";
  329.  
  330. /////////////////////////////////////////////////////////////////////
  331.  
  332. static OSStatus ReadHTTPRequest(EndpointRef worker, char *buffer)
  333.     // This routine reads the HTTP request from the worker endpoint,
  334.     // using the state machine described above, and puts it into the
  335.     // indicated buffer.  The buffer must be at least kTransferBufferSize
  336.     // bytes big.
  337.     //
  338.     // This is pretty feeble
  339.     // code (reading data one byte at a time is bad for performance),
  340.     // but it works and I'm not quite sure how to fix it.  Perhaps
  341.     // OTCountDataBytes?
  342.     //
  343.     // Also, the code does not support with requests bigger than
  344.     // kTransferBufferSize.  In practise, this isn't a problem.
  345. {
  346.     OSStatus err;
  347.     long bufferIndex;
  348.     int state;
  349.     char ch;
  350.     OTResult bytesReceived;
  351.     OTFlags junkFlags;
  352.     
  353.     OTAssert("ReadHTTPRequest: What endpoint?", worker != nil);
  354.     OTAssert("ReadHTTPRequest: What buffer?", buffer != nil);
  355.     
  356.     bufferIndex = 0;
  357.     state = kWorkerWaitingForCR1;
  358.     do {    
  359.         bytesReceived = OTRcv(worker, &ch, sizeof(char), &junkFlags);
  360.         if (bytesReceived >= 0) {
  361.             OTAssert("ReadHTTPRequest: Didn't read the expected number of bytes", bytesReceived == sizeof(char));
  362.             
  363.             err = noErr;
  364.  
  365.             // Put the character into the buffer.
  366.             
  367.             buffer[bufferIndex] = ch;
  368.             bufferIndex += 1;
  369.             
  370.             // Check that we still have space to include our null terminator.
  371.             
  372.             if (bufferIndex >= kTransferBufferSize) {
  373.                 err = -1;
  374.             }
  375.             
  376.             // Do the magic state machine.  Note the use of
  377.             // hardwired numbers for CR and LF.  This is correct
  378.             // because the Internet standards say that these
  379.             // numbers can't change.  I don't use \n and \r
  380.             // because these values change between various C
  381.             // compilers on the Mac.
  382.             
  383.             switch (ch) {
  384.                 case 13:
  385.                     switch (state) {
  386.                         case kWorkerWaitingForCR1:
  387.                             state = kWorkerWaitingForLF1;
  388.                             break;
  389.                         case kWorkerWaitingForCR2:
  390.                             state = kWorkerWaitingForLF2;
  391.                             break;
  392.                         default:
  393.                             state = kWorkerWaitingForCR1;
  394.                             break;
  395.                     }
  396.                     break;
  397.                 case 10:
  398.                     switch (state) {
  399.                         case kWorkerWaitingForLF1:
  400.                             state = kWorkerWaitingForCR2;
  401.                             break;
  402.                         case kWorkerWaitingForLF2:
  403.                             state = kWorkerDone;
  404.                             break;
  405.                         default:
  406.                             state = kWorkerWaitingForCR1;
  407.                             break;
  408.                     }
  409.                     break;
  410.                 default:
  411.                     state = kWorkerWaitingForCR1;
  412.                     break;
  413.             }
  414.         } else {
  415.             err = bytesReceived;
  416.         }
  417.     } while ( err == noErr && state != kWorkerDone );
  418.  
  419.     if (err == noErr) {
  420.         // Append the null terminator that turns the HTTP request into a C string.
  421.         buffer[bufferIndex] = 0;
  422.     }
  423.  
  424.     return (err);        
  425. }
  426.  
  427. /////////////////////////////////////////////////////////////////////
  428.  
  429. static OSStatus CopyFileToEndpoint(const FSSpec *fileSpec, char *buffer, EndpointRef worker)
  430.     // Copy the file denoted by fileSpec to the endpoint.  buffer is a
  431.     // temporary buffer of size kTransferBufferSize.  Initially buffer
  432.     // contains a C string that is the HTTP header to output.  After that,
  433.     // the routine uses buffer as temporary storage.  We do this because
  434.     // we want any errors opening the file to be noticed before we send
  435.     // the header saying that the request went through successfully.
  436. {
  437.     OSStatus err;
  438.     OSStatus junk;
  439.     long bytesToSend;
  440.     long bytesThisTime;
  441.     short fileRefNum;
  442.     
  443.     err = FSpOpenDF(fileSpec, fsRdPerm, &fileRefNum);
  444.     if (err == noErr) {
  445.         err = GetEOF(fileRefNum, &bytesToSend);
  446.         
  447.         // Write the HTTP header out to the endpoint.
  448.         
  449.         if (err == noErr) {
  450.             err = OTSndQ(worker, buffer, OTStrLength(buffer));
  451.         }
  452.         
  453.         // Copy the file in kTransferBufferSize chunks to the endpoint.
  454.         
  455.         while (err == noErr && bytesToSend > 0) {
  456.             if (bytesToSend > kTransferBufferSize) {
  457.                 bytesThisTime = kTransferBufferSize;
  458.             } else {
  459.                 bytesThisTime = bytesToSend;
  460.             }
  461.             err = FSReadQ(fileRefNum, bytesThisTime, buffer);
  462.             if (err == noErr) {
  463.                 err = OTSndQ(worker, buffer, bytesThisTime);
  464.             }
  465.             bytesToSend -= bytesThisTime;
  466.         }
  467.         
  468.         // Clean up.
  469.         junk = FSClose(fileRefNum);
  470.         OTAssert("WorkerThreadProc: Could not close file", junk == noErr);
  471.     }
  472.     
  473.     return (err);
  474. }
  475.  
  476. /////////////////////////////////////////////////////////////////////
  477.  
  478. static pascal OSStatus WorkerThreadProc(WorkerContextPtr context)
  479.     // This routine is the starting routine for the worker thread.
  480.     // The thread is responsible for reading an HTTP request from
  481.     // an endpoint, processing the requesting and writing the results
  482.     // back to the endpoint.
  483. {
  484.     OSStatus err;
  485.     OSStatus junk;
  486.     char *buffer = nil;
  487.     char *errStr;
  488.     char fileName[256];
  489.     char mimeType[256];
  490.     FSSpec fileSpec;
  491.     
  492.     printf("WorkerThreadProc: Starting\n");
  493.     fflush(stdout);
  494.     OTAssert("WorkerThreadProc: Context is nil!", context != nil);
  495.     OTAssert("WorkerThreadProc: Worker endpoint is nil!", context->worker != nil);
  496.  
  497.     // Allocate the transfer buffer in the heap.
  498.     
  499.     err = noErr;
  500.     buffer = OTAllocMem(kTransferBufferSize);
  501.     if (buffer == nil) {
  502.         err = kENOMEMErr;
  503.     }
  504.  
  505.     // Read the request into the transfer buffer.
  506.     
  507.     if (err == noErr) {
  508.         err = ReadHTTPRequest(context->worker, buffer);
  509.     }
  510.     
  511.     if (err == noErr) {
  512.  
  513.         // Get the requested file name (and it's mimeType) from the
  514.         // HTTP request in the transfer buffer.
  515.         
  516.         err = ExtractRequestedFileName(buffer, fileName, mimeType);
  517.         
  518.         if (err == noErr) {
  519.  
  520.             // Create the appropriate HTTP response in the buffer.
  521.             
  522.             sprintf(buffer, gHTTPHeader, mimeType);
  523.  
  524.             // Copy the file (with preceding HTTP header) to the endpoint.
  525.             
  526.             (void) FSMakeFSSpec(context->vRefNum, context->dirID, C2PStr(fileName), &fileSpec);
  527.             err = CopyFileToEndpoint(&fileSpec, buffer, context->worker);
  528.         }
  529.         
  530.         // Handle any errors by sending back an appropriate error header.
  531.         
  532.         if (err != noErr) {
  533.             switch (err) {
  534.                 case fnfErr:
  535.                     errStr = "File Not Found";
  536.                     break;
  537.                 default:
  538.                     errStr = "Unknown Error";
  539.                     break;
  540.             }
  541.             sprintf(buffer, gDefaultOutputText, err, errStr);
  542.             err = OTSndQ(context->worker, buffer, OTStrLength(buffer));
  543.         }
  544.     }
  545.     
  546.     // Shut down the endpoint and clean up the WorkerContext.
  547.     
  548.     if (err == noErr) {
  549.         err = OTSndOrderlyDisconnect(context->worker);
  550.         if (err == noErr) {
  551.             err = OTRcvOrderlyDisconnect(context->worker);
  552.         }
  553.     }
  554.  
  555.     junk = OTCloseProvider(context->worker);
  556.     OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  557.     
  558.     OTFreeMem(context);
  559.  
  560.     if (buffer != nil) {
  561.         OTFreeMem(buffer);
  562.     }
  563.  
  564.     printf("WorkerThreadProc: Stopping with final result %d.\n", err);
  565.     fflush(stdout);
  566.     
  567.     return (noErr);
  568. }
  569.  
  570. /////////////////////////////////////////////////////////////////////
  571.  
  572. OSStatus RunHTTPServer(InetHost ipAddr, short vRefNum, long dirID)
  573.     // This routine runs an HTTP server.  It doesn't return until
  574.     // someone sets gQuitNow, so you should most probably call this
  575.     // routine on its own thread.  ipAddr is the IP address that
  576.     // the server listens on.  Specify kOTAnyInetAddress to listen
  577.     // on all IP addresses on the machine; specify an IP address
  578.     // to listen on a specific address.  vRefNum and dirID point
  579.     // to the root directory of the HTTP information to be served.
  580.     //
  581.     // The routine creates a listening endpoint and listens for connection 
  582.     // requests on that endpoint.  When a connection request arrives, it creates 
  583.     // a new worker thread (with accompanying endpoint) and accepts the connection
  584.     // on that thread.
  585.     //
  586.     // Note the use of the "tilisten" module which prevents multiple
  587.     // simultaneous T_LISTEN events coming from the transport provider,
  588.     // thereby greatly simplifying the listen/accept sequence.
  589. {
  590.     OSStatus err;
  591.     EndpointRef listener;
  592.     TBind bindReq;
  593.     InetAddress ipAddress;
  594.     InetAddress remoteIPAddress;
  595.     TCall call;
  596.     ThreadID workerThread;
  597.     OSStatus junk;
  598.     WorkerContextPtr workerContext;
  599.     TEndpointInfo Info;
  600.     char    buf[128];
  601.     
  602.     // display IP address in String
  603.     OTInetHostToString(ipAddr, buf);
  604.     printf("HTTP Server on <%s> Starting.\n", buf);
  605.  
  606.     fflush(stdout);
  607.  
  608.     // Create the listen endpoint.
  609.     
  610.     // RRK comments added 8/27/97
  611.     // In order for the IP address to be re-used after quitting this sample program and
  612.     // restarting it, the "ReuseAddr" option must be set.
  613.     // One should be able to set the "ReuseAddr" option as part of the configuration string
  614.     // however, if you try to do this along with specifying the use of the tilisten
  615.     // module, the following code hangs the system hard.  As an alternative, the 
  616.     // endpoint is created with the tilisten module layered above tcp.  After that the
  617.     // OTOptionManagement call is made to set this option.
  618.     // RRK Comments end
  619.     
  620.     //listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp(ReuseAddr=1)"), 0, nil, &err);
  621.     listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp"), 0, &Info, &err);
  622.     
  623.     // RRK addition 8/27/97
  624.     // set the ReuseAddr option
  625.     if (err == noErr) {
  626.         junk = DoNegotiateIPReuseAddrOption(listener, true);
  627.         OTAssert("Unable to negotiate raw mode for listener endpoint", junk == noErr);
  628.     }    
  629.     // end RRK addition 8/27/97
  630.  
  631.     // Set the endpoint mode and bind it to the appropriate IP address.
  632.     
  633.     if (err == noErr) {
  634.         SetDefaultEndpointModes(listener);
  635.         OTInitInetAddress(&ipAddress, 80, ipAddr);    // port & host ip
  636.         bindReq.addr.buf = (UInt8 *) &ipAddress;
  637.         bindReq.addr.len = sizeof(ipAddress);
  638.         bindReq.qlen = 1;
  639.         err = OTBind(listener, &bindReq, nil);
  640.     }
  641.     
  642.     while (err == noErr) {
  643.  
  644.         // Listen for connection attempts...
  645.         
  646.         OTMemzero(&call, sizeof(TCall));
  647.         call.addr.buf = (UInt8 *) &remoteIPAddress;
  648.         call.addr.maxlen = sizeof(remoteIPAddress);
  649.         err = OTListen(listener, &call);
  650.  
  651.         // ... then spool a worker thread for this connection.
  652.         
  653.         if (err == noErr) {
  654.         
  655.             // Create the worker context.
  656.         
  657.             workerThread = kNoThreadID;
  658.             workerContext = OTAllocMem(sizeof(WorkerContext));
  659.             if (workerContext == nil) {
  660.                 err = kENOMEMErr;
  661.             } else {
  662.                 workerContext->worker = nil;
  663.                 workerContext->vRefNum = vRefNum;
  664.                 workerContext->dirID = dirID;
  665.             }
  666.             
  667.             // Open the worker endpoint.
  668.             
  669.             if (err == noErr) {
  670.                 workerContext->worker = OTOpenEndpoint(OTCreateConfiguration("tcp"), 0, nil, &err);
  671.                 if (err == noErr) {
  672.                     SetDefaultEndpointModes(workerContext->worker);
  673.                 }
  674.             }
  675.             
  676.             // Create the worker thread.
  677.             
  678.             if (err == noErr) {
  679.                 err = NewThread(kCooperativeThread,
  680.                                 (ThreadEntryProcPtr) WorkerThreadProc, workerContext,
  681.                                 0, kNewSuspend | kCreateIfNeeded,
  682.                                 nil,
  683.                                 &workerThread);
  684.             }
  685.             
  686.             // Accept the connection on the thread.
  687.             
  688.             if (err == noErr) {
  689.                 err = OTAccept(listener, workerContext->worker, &call);
  690.             }
  691.             
  692.             // Schedule the thread for execution.
  693.             
  694.             if (err == noErr) {
  695.                 err = SetThreadState(workerThread, kReadyThreadState, kNoThreadID);
  696.             }
  697.             
  698.             // Clean up on error.
  699.             
  700.             if (err != noErr) {
  701.                 if (workerContext != nil) {
  702.                     if (workerContext->worker != nil) {
  703.                         junk = OTCloseProvider(workerContext->worker);
  704.                         OTAssert("StartHTTPServer: Could not close worker", junk == noErr);
  705.                     }
  706.                     OTFreeMem(workerContext);
  707.                 }
  708.                 if (workerThread != kNoThreadID) {
  709.                     junk = DisposeThread(workerThread, nil, true);
  710.                     OTAssert("StartHTTPServer: DisposeThread failed", junk == noErr);
  711.                 }
  712.                 printf("StartHTTPServer: Failed to spool worker, error %d.\n", err);
  713.                 fflush(stdout);
  714.                 err = noErr;
  715.             }
  716.         }
  717.     }
  718.     
  719.     // Clean up the listener endpoint.
  720.     
  721.     if (listener != nil) {
  722.         junk = OTCloseProvider(listener);
  723.         OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  724.     }
  725.  
  726.     printf("HTTP Server on %08x: Stopping.\n", ipAddr);
  727.     fflush(stdout);
  728.     
  729.     return (err);
  730. }
  731.